'use client'

import { Fragment, useState } from 'react'
import { Dialog, Transition } from '@headlessui/react'
import { useForm } from 'react-hook-form'
import { createProduct } from '@/actions/product'
import { FormInput } from '@/components/ui/form'
import { useCategories } from '@/hooks/use-categories'

// 预定义的单位选项
const UNIT_OPTIONS = [
  { value: '件', label: '件' },
  { value: '个', label: '个' },
  { value: '箱', label: '箱' },
  { value: 'kg', label: 'kg' },
  { value: '包', label: '包' },
  { value: '瓶', label: '瓶' },
  { value: '盒', label: '盒' },
  { value: '套', label: '套' },
] as const

type ProductUnit = (typeof UNIT_OPTIONS)[number]['value']

interface CreateProductDialogProps {
  open: boolean
  onClose: () => void
}

export function CreateProductDialog({ open, onClose }: CreateProductDialogProps) {
  const { categories } = useCategories()
  const { register, handleSubmit, formState: { errors }, reset } = useForm({
    defaultValues: {
      name: '',
      code: '',
      description: '',
      price: '',
      unit: '件',
      stock: '',
      categoryId: ''
    }
  })

  const onSubmit = async (data: any) => {
    try {
      await createProduct(data)
      reset()
      onClose()
    } catch (error) {
      console.error('创建商品失败:', error)
    }
  }

  return (
    <Transition show={open} as={Fragment}>
      <Dialog onClose={onClose} className="relative z-50">
        <Transition.Child
          as={Fragment}
          enter="ease-out duration-300"
          enterFrom="opacity-0"
          enterTo="opacity-100"
          leave="ease-in duration-200"
          leaveFrom="opacity-100"
          leaveTo="opacity-0"
        >
          <div className="fixed inset-0 bg-black/30" />
        </Transition.Child>

        <div className="fixed inset-0 overflow-y-auto">
          <div className="flex min-h-full items-center justify-center p-4">
            <Transition.Child
              as={Fragment}
              enter="ease-out duration-300"
              enterFrom="opacity-0 scale-95"
              enterTo="opacity-100 scale-100"
              leave="ease-in duration-200"
              leaveFrom="opacity-100 scale-100"
              leaveTo="opacity-0 scale-95"
            >
              <Dialog.Panel className="w-full max-w-md transform overflow-hidden rounded-2xl bg-white p-6 text-left align-middle shadow-xl transition-all">
                <Dialog.Title as="h3" className="text-lg font-medium leading-6 text-gray-900">
                  添加商品
                </Dialog.Title>
                <form onSubmit={handleSubmit(onSubmit)} className="mt-4 space-y-4">
                  <FormInput
                    label="商品名称"
                    {...register('name', { required: '请输入商品名称' })}
                    error={errors.name?.message}
                  />
                  <FormInput
                    label="商品编码"
                    {...register('code', { required: '请输入商品编码' })}
                    error={errors.code?.message}
                  />
                  <FormInput
                    label="商品描述"
                    {...register('description')}
                    error={errors.description?.message}
                  />
                  <div className="grid grid-cols-2 gap-4">
                    <FormInput
                      label="价格"
                      type="number"
                      step="0.01"
                      {...register('price', { required: '请输入价格' })}
                      error={errors.price?.message}
                    />
                    <div>
                      <label className="block text-sm font-medium text-gray-900">单位</label>
                      <select
                        {...register('unit', { required: '请选择单位' })}
                        className="form-select block w-full px-4 py-2.5 rounded-lg border border-gray-300 bg-white text-gray-900 shadow-sm focus:border-blue-500 focus:ring-1 focus:ring-blue-500"
                      >
                        <option value="">请选择单位</option>
                        {UNIT_OPTIONS.map(option => (
                          <option key={option.value} value={option.value}>
                            {option.label}
                          </option>
                        ))}
                      </select>
                      {errors.unit?.message && (
                        <span className="text-sm text-red-500">{errors.unit.message}</span>
                      )}
                    </div>
                  </div>
                  <FormInput
                    label="库存"
                    type="number"
                    {...register('stock', { required: '请输入库存' })}
                    error={errors.stock?.message}
                  />
                  <div>
                    <label className="block text-sm font-medium text-gray-900">商品分类</label>
                    <select
                      {...register('categoryId', { required: '请选择商品分类' })}
                      className="form-select block w-full px-4 py-2.5 rounded-lg border border-gray-300 bg-white text-gray-900 shadow-sm focus:border-blue-500 focus:ring-1 focus:ring-blue-500"
                    >
                      <option value="">请选择分类</option>
                      {categories.map(category => (
                        <option key={category.id} value={category.id}>
                          {category.name}
                        </option>
                      ))}
                    </select>
                    {errors.categoryId?.message && (
                      <span className="text-sm text-red-500">{errors.categoryId.message}</span>
                    )}
                  </div>

                  <div className="mt-6 flex justify-end gap-3">
                    <button
                      type="button"
                      onClick={onClose}
                      className="px-4 py-2 text-sm font-medium text-gray-700 hover:bg-gray-50 border border-gray-300 rounded-md"
                    >
                      取消
                    </button>
                    <button
                      type="submit"
                      className="px-4 py-2 text-sm font-medium text-white bg-blue-500 hover:bg-blue-600 rounded-md"
                    >
                      创建
                    </button>
                  </div>
                </form>
              </Dialog.Panel>
            </Transition.Child>
          </div>
        </div>
      </Dialog>
    </Transition>
  )
} 